package com.example.fence.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Lazy;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import java.util.Set;

import static com.example.fence.util.FenceStoreUtil.deviceReceiveEmail;
import static com.example.fence.util.FenceStoreUtil.deviceSendEmail;


@Service
@Slf4j
public class MailService {

    @Autowired
    private JavaMailSender javaMailSender;


    public void sendSimpleMail(String IMEI,String lat,String lon) throws Exception {
        // TODO:  test
        Set<String> to_list = deviceReceiveEmail.get(IMEI);
        String[] recipients = to_list.toArray(new String[to_list.size()]);
        String subject = "电子围栏报警提醒";
        String text = EmailTextBuilder(IMEI,lat,lon);
        SimpleMailMessage message = new SimpleMailMessage();
        StringBuilder to_bulider=new StringBuilder();
        for(String to_temp  : to_list) {
            to_bulider.append(to_temp);
        }
        String to = to_bulider.toString();
        message.setTo(recipients);
        message.setFrom(deviceSendEmail.get(IMEI).replace("[","").replace("]",""));
        message.setSubject(subject);
        message.setText(text);
        javaMailSender.send(message);
        log.info("emil to {} publish success \nsubject: {}\ntext:{}",to,subject,text);
    }
    private String EmailTextBuilder(String IMEI,String lat,String lon){
        String currentTime=CurrentTime();
        return "您好，贵公司所监控的车辆"+IMEI+"于今日"+currentTime+"，驶出电子围栏，现位于经度:"+lon+"纬度"+lat+"，请您尽快处理。";
    }


    public String CurrentTime() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH时mm分");
        return now.format(formatter);
    }


}
